<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Session;

class OrderController extends Controller
{
    public function order(Request $request)
    {
        $data = $request -> all();
        // dd($data);
        $gids = $data['gid'];
        $gid = explode(',', $gids);
        // dd($gid);
        // dd(Session('home'));
        $uid = Session('home') -> id;
        //获取收货地址
        $ads = DB::table('t_info') -> where('uid', $uid) -> get();
        // dd($ads);
        // dd($uid);
        $res = [];
        for($i=0; $i<count($gid);$i++)
        {
            $res[$i] = DB::table('t_car') -> where('gid', $gid[$i]) -> whereIn('uid',[$uid]) -> get();
        }
        // dd($res); 
        //获取商品数量
        $num = [];
        for ($i=0; $i < count($res); $i++) { 
            // dd($res[$i]['0'] -> count);
            // dd($res[$i] -> count);
            $num[$i] = $res[$i]['0'] -> count;
        }
        // dd($num);
        //获取商品价格
        $g_price = [];
        for ($i=0; $i <count($gid); $i++) { 
            $g_price[$i] = DB::table('t_goods') -> where('gid', $gid[$i]) -> value('gprice');
        }
        // dd($g_price);
        //计算总价
        $zje = 0;
        for ($i=0; $i < count($num); $i++) { 
            $zje += $num[$i] * $g_price[$i];
        }
        // dd($zje);
        return view('home.order.index',['res'=> $res, 'zje' => $zje, 'ads' => $ads]);
        // dd($request -> order_list);
        // dd(session('goods_list'));
    }
    //结算提交
    public function ajax(Request $request){
    	// dd($request -> all());

        // redirect('home.order.index');
        return view('home.order.index',['request' => $request -> all()]);
        // return redirect()->route('/order/index', [$request]);
    }
    //提交订单
    public function tijiao(Request $request)
    {
        $data = $request -> except('_token','zje');
        // dd($data);
        $order_num = rand(time(), 10);
        $uid = session('home') -> id;
        $data['uid'] = $uid;
        $gids = session('goods_list');

        foreach ($gids as $k => $v) {
            $data['gid'] = $k;
            $data['count'] = $v['count'];
            $data['order_num'] = $order_num;
            $res = DB::table('t_order') -> insert($data);
        }
        $zjenum = $request -> only('zje');
        $zje = $zjenum['zje'];
        // dd($zje);
        //随机生成订单号
        if($res)
        {
            return redirect('/order/zhifu') -> with('zje', $zje);
        }else
        {
            return 0;
        }
        
    }

    //支付
    public function zhifu()
    {
        $zje = session('zje');
        return view('home.order.zhifu', ['zje' => $zje]);
    }
}
